package com.generalaj.io.util;

import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
import org.mozilla.intl.chardet.nsPSMDetector;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by wangxin on 2017/3/2.
 */
public class FileCharsetDetector {
    private boolean found = false;
    private String encoding=null;
    private nsDetector det = new nsDetector(nsPSMDetector.SIMPLIFIED_CHINESE);
    public FileCharsetDetector(){
        det.Init(new nsICharsetDetectionObserver() {
            public void Notify(String charset) {
                found = true;
                encoding=charset;
            }
        });
    }
    public String getFileEncodeing(File path) throws IOException {

        BufferedInputStream inbuff=new BufferedInputStream(new FileInputStream(path));

        boolean isAscii = true;
        try{
            byte[] b=new byte[1024*5];
            int len=0;
            boolean done = false;
            while((len=inbuff.read(b))!=-1){
                if (isAscii)
                    isAscii = det.isAscii(b, len);
                if (!isAscii && !done)
                    done = det.DoIt(b, len, false);
            }
        }finally {
            IOUtil.close(inbuff);
        }
        det.DataEnd();
        if (isAscii) {
            encoding = "ASCII";
            found = true;
        }
        if (!found) {
            String prob[] = det.getProbableCharsets();
            if (prob.length > 0) {
                encoding = prob[0];
            } else {
                return null;
            }
        }
        return encoding;
    }

}
